/*
 * TagSelection.java
 * 
 *  This class submits the username and password (as entered in the
 *  text boxes in the main GUI) to a PHP script that in turn obtains
 *  a list of tags appropriate for the user's current project.
 *  
 *  These tags are printed in the PHP file in XML format (see tags_xml.php).
 *  
 *  XML Format:
 *  <Tags>
 *  	<Tag tagid='1' tagtext='my tag' />
 *  	<Tag tagid='2' tagtext='my other tag' />
 *  </Tags>
 *  
 *  This class parses the XML in the createTagsFromXML() function.
 *  
 *  After selecting the tags appropriate for the recorded sound
 *  and images, the tagsToString() function produces a comma-separated
 *  string of the ID of each string (which, in turn, will be passed
 *  to the mupload.php script when the files are uploaded).
 *  
 */

package com.android.UrbanRemix;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.*;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class TagSelection extends ListActivity {

	final Context myContext = this;
	private String tagsId[], tagsArray[];
	private String tags, username, password;
	public String flag;
	Document doc = null;
	URLConnection urlConn;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		// Request.notification( myContext
		// ,"Please Wait","The Tags are being Loaded");
		super.onCreate(savedInstanceState);

		// Bundle b = this.getIntent().getExtras();
		// this.username = b.getString("username");
		// this.password = b.getString("password");

		// Request.notification( myContext
		// ,"Please Wait","The Tags are being Loaded");
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);
		this.username = mySharedPreferences.getString("username", "");
		this.password = mySharedPreferences.getString("password", "");
		String responseFromServer = loadTagsFromWeb(UrbanRemix_New.TAGS_XML);

		if (responseFromServer == "Success") {
			createTagsFromXml();
		} else
			backToMain(RESULT_CANCELED, responseFromServer);

		setContentView(R.layout.tag);

		final ListView listView = getListView();

		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		((android.widget.Button) findViewById(R.id.tagdone))
				.setOnClickListener(new View.OnClickListener() {
					public void onClick(View view) {
						tagsToString();
						backToMain(RESULT_OK, null);

					}
				});
	}

	private String loadTagsFromWeb(String urlstring) {

		int responsecode = 0;
		HttpURLConnection conn;

		try {
			URL url = new URL(urlstring);
			urlConn = url.openConnection();

			conn = (HttpURLConnection) urlConn;

			String lineEnd = "\r\n"; // newline
			String twoHyphens = "--"; // prefix
			String boundary = "*****";

			// Allow Inputs
			conn.setDoInput(true);

			// Allow Outputs
			conn.setDoOutput(true);

			// Don't use a cached copy.
			conn.setUseCaches(false);

			// Use a post method.
			conn.setRequestMethod("POST");

			conn.setRequestProperty("Connection", "Keep-Alive");

			conn.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);

			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

			// send username data
			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\"username\"");
			dos.writeBytes(lineEnd + lineEnd);
			dos.writeBytes(username);
			dos.writeBytes(lineEnd);

			// send password data
			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\"password\"");
			dos.writeBytes(lineEnd + lineEnd);
			dos.writeBytes(password);
			dos.writeBytes(lineEnd);
		} catch (MalformedURLException e) {
			return new String("Error: Malformed URL Exception");
		} catch (IOException e) {
			return new String(
					"Error: IO Exception. Check your internet connection.");
		} catch (Exception e) {
			return new String("Error: Encountered error");
		}

		try {
			responsecode = 0;
			responsecode = conn.getResponseCode();
		} catch (Exception e) {
			return new String("Error");
		}

		if (responsecode > 200) {
			return new String("Error: HTTP Response code " + responsecode);
		}

		return "Success";
	}

	private void tagsToString() {
		ListView lv = getListView();
		String tempstring = new String();

		for (int i = 0; i < lv.getCount(); i++) {
			if (lv.isItemChecked(i))
				tempstring = tempstring + tagsId[i] + ",";
		}

		if (tempstring.length() > 1)
			tempstring = tempstring.substring(0, tempstring.lastIndexOf(","));
		tags = tempstring;

	}

	private void backToMain(int resultCode, String returnMessage) {
		Intent intentout = new Intent();
		if (returnMessage == null)
			returnMessage = "Recording successfully tagged";
		intentout.putExtra("com.android.urbanremix.Tags", tags);
		intentout.putExtra("com.android.urbanremix.ReturnMessage",
				returnMessage);
		setResult(resultCode, intentout);

		finish();
	}

	private void createTagsFromXml() {
		try {
			DocumentBuilderFactory docbuilderfactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docbuilder = docbuilderfactory.newDocumentBuilder();
			doc = docbuilder.parse(urlConn.getInputStream());
		} catch (IOException e) {
			Request
					.notification(myContext, "IOException",
							"Error opening url.");
		} catch (ParserConfigurationException e) {
			Request.notification(myContext, "Parser Configuration Exception",
					"Parser Configuration exception.");
		} catch (SAXException e) {
			Request.notification(myContext, "SAX Exception",
					"SAX Exception occurred.");
		}

		// check whether the XML document contained an "Error" tag
		if (doc.getElementsByTagName("Error").getLength() > 0) {
			backToMain(RESULT_CANCELED, doc.getElementsByTagName("Error").item(
					0).getAttributes().getNamedItem("message").getNodeValue());
		} else {
			NodeList tags = doc.getElementsByTagName("Tag");

			tagsArray = new String[tags.getLength()];
			tagsId = new String[tags.getLength()];

			for (int i = 0; i < tagsArray.length; i++) {
				Node tag = tags.item(i);
				NamedNodeMap tagattributes = tag.getAttributes();
				Node tagtextnode = tagattributes.getNamedItem("tagtext");
				Node tagidnode = tagattributes.getNamedItem("tagid");
				String tagid = tagidnode.getNodeValue();
				String tagtext = tagtextnode.getNodeValue();
				tagsId[i] = tagid;
				tagsArray[i] = tagtext;
			}
			setListAdapter(new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_multiple_choice,
					tagsArray));
		}
	}
}